var app = getApp()
var http = app.require('utils/http.js')
var util = app.require('utils/util.js')
var validator = require('../../../utils/validator.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        dictValueMap: {},
        dictValueItemMap: {},
        detail: {
            billDate: '',
            totalAmount: '0.00',
            productAmount: '0.00',
            freightAmount: '0.00',
            discountAmount: '0.00',
            payStatus: '0',
            status: '10',
            images: [],
        },
        products: [],
        addedProducts: [],
        images: [],

        productSelectDialogVisiable: false,
        curSelectedProductIndex: 0,
        curSelectedProduct: {},

        payStatusSelectDialogVisiable: false,
        statusSelectDialogVisiable: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.loadDictValues()
        let id = options.id || ''
        if (id != '') {
            http.request('saleBill/readExtView', {id: id}, function(res) {
                let billDateTimestamp = new Date(res.billDate + " 00:00:00").getTime()
                res.billDateTimestamp = billDateTimestamp
                if (!res.images) {
                    res['images'] = []
                }
                that.setData({
                    detail: res
                })
                

                that.parseImages()
                that.parseProducts()
            })
        } else {
            that.data.detail.billDateTimestamp = new Date().getTime()
            that.data.detail.billDate = util.getCurDate()

            that.setData({
                detail: that.data.detail
            })
        }

        that.loadAllProducts()
    },

    loadDictValues() {
        let that = this
        http.loadDictValue('payStatus, saleBillStatus', function(data) {
            that.setData({
                dictValueMap: data.dictValueMap,
                dictValueItemMap: data.dictValueItemMap,
            })
        })
    },

    loadAllProducts() {
        let that = this
        http.request('product/readAll', {}, function(res) {
            that.setData({
                products: res
            })
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    bindInput(e) {
        let that = this
        let dataset = e.currentTarget.dataset;
        let value = e.detail.value;
        if (!value) {
            value = e.detail
        }
        let index = dataset.index;
        if (index != undefined) {
          this.data[dataset.obj][index][dataset.item] = value;
          this.setData({
            [dataset.obj]: this.data[dataset.obj]
          })
          
          if (dataset.obj == 'addedProducts' && dataset.item == 'price') {
              that.calProductAmount()
          }

          if (dataset.obj == 'addedProducts' && dataset.item == 'num') {
            that.calProductAmount()
          }
        } else {
          this.data[dataset.obj][dataset.item] = value;
          this.setData({
            [dataset.obj]: this.data[dataset.obj]
          })

          if (dataset.obj == 'detail' && dataset.item == 'freightAmount') {
                that.calProductAmount()
            }

            if (dataset.obj == 'detail' && dataset.item == 'discountAmount') {
                that.calProductAmount()
            }
        }
      },

    gotoSelectCustomerPage() {
        let that = this
        let customerId = that.data.detail.customerId
        let page = '/pages/customer/select/index'
        if (customerId) {
            page = page + '?selectedId=' + customerId
        }
        wx.navigateTo({
          url: page,
        })
    },

    setSelectedCustomer(customer) {
        let that = this
        that.data.detail.customerId = customer.id
        that.data.detail.customerName = customer.name
        that.data.detail.customerLinkman = customer.linkman
        that.data.detail.customerLinkPhone = customer.linkPhone
        that.data.detail.customerAreaId = customer.areaId
        that.data.detail.customerAreaInfo = customer.areaInfo
        that.data.detail.customerAddress = customer.address
        that.setData({
            detail: that.data.detail
        })
    },

    showProductSelectDialog(e) {
        let that = this
        let dataset = e.currentTarget.dataset
        let index = dataset.index

        let curSelectedProduct = that.data.addedProducts[index]
        that.setData({
            curSelectedProductIndex: index,
            curSelectedProduct: curSelectedProduct,
            productSelectDialogVisiable: true
        })
    },

    hideProductSelectDialog(e) {
        let that = this
        
        let curSelectedProduct = {}
        that.setData({
            curSelectedProduct: curSelectedProduct,
            productSelectDialogVisiable: false
        })
    },

    selectBillDate(e) {
        let that = this
        let billDateTimestamp = e.detail
        that.data.detail.billDateTimestamp = billDateTimestamp
        that.data.detail.billDate = util.formatTime(new Date(billDateTimestamp)).substring(0, 10)
        that.setData({
            detail: detail,
            billDateSelectDialogVisiable: false
        });
    },

    cancelSelectBillDate() {
        let that = this
        that.setData({
            billDateSelectDialogVisiable: false
        });
    },

    selectProduct(e) {
        let that = this
        let dataset = e.currentTarget.dataset
        let id = dataset.name
        for (var i = 0; i < that.data.products.length; ++i) {
            if (that.data.products[i].id == id) {

                that.data.addedProducts[that.data.curSelectedProductIndex]['productId'] = id
                that.data.addedProducts[that.data.curSelectedProductIndex]['name'] = that.data.products[i]['name']
                that.data.addedProducts[that.data.curSelectedProductIndex]['price'] = that.data.products[i]['price']
                that.setData({
                    addedProducts: that.data.addedProducts,
                    productSelectDialogVisiable: false
                })

                that.calProductAmount()
                break;
            }
        }
    },

    addProduct(e) {
        let that = this
        let newProduct = {
            productId: '',
            name: '',
            price: '',
            num: ''
        }
        that.data.addedProducts.push(newProduct)

        that.setData({
            addedProducts: that.data.addedProducts
        })
    },

    deleteProduct(e) {
        let that = this
        let dataset = e.currentTarget.dataset
        let index = dataset.index

        that.data.addedProducts.splice(index, 1)
        that.setData({
            addedProducts: that.data.addedProducts
        })

        that.calProductAmount()
    },

    calProductAmount() {
        let that = this

        let totalProductAmount = 0.00
        for (var i = 0; i < that.data.addedProducts.length; ++i) {
            let tmpProduct = that.data.addedProducts[i]
            if (tmpProduct.price && tmpProduct.num 
                && validator.isPriceNumber(tmpProduct.price) 
                && validator.isPriceNumber(tmpProduct.num)) {
                    let productAmount = (parseFloat(tmpProduct.price) * parseFloat(tmpProduct.num)).toFixed(2)
                    tmpProduct['productAmount'] = productAmount

                    totalProductAmount = totalProductAmount + parseFloat(productAmount)
                }
        }


        let totalAmount = totalProductAmount
        if (that.data.detail.freightAmount && validator.isPriceNumber(that.data.detail.freightAmount)) {
            totalAmount += parseFloat(that.data.detail.freightAmount)
        }

        if (that.data.detail.discountAmount && validator.isPriceNumber(that.data.detail.discountAmount)) {
            totalAmount -= parseFloat(that.data.detail.discountAmount)
        }

        that.data.detail.productAmount = totalProductAmount.toFixed(2)
        that.data.detail.totalAmount = totalAmount.toFixed(2)

        that.setData({
            detail: that.data.detail
        })
    },

    showPayStatusSelectDialog() {
        let that = this
        that.setData({
            payStatusSelectDialogVisiable: true
        })
    },

    hidePayStatusSelectDialog() {
        let that = this
        that.setData({
            payStatusSelectDialogVisiable: false
        })
    },

    selectPayStatus(e) {
        let that = this
        const { name } = e.currentTarget.dataset;
        that.data.detail.payStatus = name
        that.setData({
            detail: that.data.detail,
            payStatusSelectDialogVisiable: false
        })
    },

    showStatusSelectDialog() {
        let that = this
        that.setData({
            statusSelectDialogVisiable: true
        })
    },

    hideStatusSelectDialog() {
        let that = this
        that.setData({
            statusSelectDialogVisiable: false
        })
    },

    selectStatus(e) {
        let that = this
        let { name } = e.currentTarget.dataset
        that.data.detail.status = name
        that.setData({
            detail: that.data.detail,
            statusSelectDialogVisiable: false
        })
    },

    showBillDateSelectDialog() {
        let that = this
        that.setData({
            billDateSelectDialogVisiable: true
        })
    },

    hideBillDateSelectDialog() {
        let that = this
        that.setData({
            billDateSelectDialogVisiable: false
        })
    },

    uploadImages(e) {
        let that = this
        
        let imgs = e.detail.file
        let data = {
          uploadDir: 'saleBill'
        }

        for (var i = 0; i < imgs.length; i++) {
          http.uploadImage('common/uploadImage', imgs[i].url, data, function(res) {

            let img = {
              id: res.id,
              path: res.path
            };
            
            that.data.detail.images.push(img);
            that.setData({
                detail: that.data.detail
            })

            that.parseImages()
          });
        }
    },

    deleteImage(e) {
        let that = this
        let deleteImageIndex = e.detail.index
        that.data.detail.images.splice(deleteImageIndex, 1)
        that.setData({
            detail: that.data.detail
        })
        that.parseImages()
    },

    parseImages() {
        let that = this
        let tmpImages = []
        if (that.data.detail.images) {
            for (var i = 0; i < that.data.detail.images.length; ++i) {
                let image = { 
                    url: util.getImageUrl(that.data.detail.images[i].path) 
                }
                tmpImages.push(image)
            }
        }

        that.setData({
            images: tmpImages
        })
    },

    parseProducts() {
        let that = this
        let tmpProducts = []
        for (var i = 0; i < that.data.detail.products.length; ++i) {
            tmpProducts.push(that.data.detail.products[i])
        }

        that.data.detail.products = []
        that.setData({
            addedProducts: tmpProducts,
            detail: that.data.detail
        })
    },

    submit() {
        let that = this
        
        if (validator.isEmptyObj(that.data.detail.status)) {
            util.toast('请选择销售单状态', 'none', 2000)
            return
        }

        if (validator.isEmptyObj(that.data.detail.billDate)) {
            util.toast('请选择销售单日期', 'none', 2000)
            return
        }

        if (validator.isEmptyObj(that.data.detail.customerId)) {
            util.toast('请选择客户', 'none', 2000)
            return
        }
        
        if (that.data.addedProducts.length == 0) {
            util.toast('请添加商品', 'none', 2000)
            return
        }
        for (var i = 0; i < that.data.addedProducts.length; ++i) {
            let tmpProduct = that.data.addedProducts[i]
            if (validator.isEmptyObj(tmpProduct.productId)) {
                util.toast('请选择商品', 'none', 2000)
                return
            }
            let productName = tmpProduct.productName
            if (!validator.isPriceNumber(tmpProduct.price)) {
                util.toast('请填写商品‘' + productName + '’单价', 'none', 2000)
                return
            }
            if (!validator.isPriceNumber(tmpProduct.num)) {
                util.toast('请填写商品‘' + productName + '’数量', 'none', 2000)
                return
            }
        }
        if (validator.isEmptyObj(that.data.detail.payStatus)) {
            util.toast('请选择付款状态', 'none', 2000)
            return
        }
        if (that.data.detail.payStatus == '1' 
            && (validator.isEmptyObj(that.data.detail.payAmount) || !validator.isPriceNumber(tmpProduct.price))) {
            util.toast('已付款金额填写不正确', 'none', 2000)
            return
        }
        
        let requestParams = that.data.detail
        let imageFileIds = []
        for (var i = 0; i < that.data.detail.images.length; ++i) {
            imageFileIds.push(that.data.detail.images[i].id)
        }
        requestParams['imageFileIds'] = imageFileIds
        requestParams['products'] = that.data.addedProducts
        http.request('saleBill/save', requestParams, function(res) {
            util.toast('保存成功', 'success', 2000, function() {
                that.refreshPrePage(that.data.detail.id ? 'update' : 'create');
                wx.navigateBack();
            })
        })
    },


    refreshPrePage(optionType) {
        let pages = getCurrentPages();
        if (pages.length > 1) {
          let prePage = pages[pages.length - 2];
            prePage.reloadAllListDatas();
        }
      },


})